import {
  Inject,
  Get,
  Post,
  Body,
  Query,
  ALL,
  Provide,
  Validate,
} from '@midwayjs/decorator';
import { BaseController, RESCODE, CoolController } from 'midwayjs-cool-core';

import { MallProductClothingEntity } from '../entity/productClothing';
import { NewSkuDTO, ListSkuDTO } from '../dto/productClothing';
import { MallProductClothingService } from '../service/productClothing';
import { MallProductService } from '../service/product';

/**
 * 对 SKU 的操作通常要联合 product，这里暂用 CoolController 提供的操作
 */
@Provide()
@CoolController({
  prefix: '/mall/product_clothing',
  api: ['info', 'delete', 'update'], // 根据 id 获取、删除、更新单个 sku 信息
  entity: MallProductClothingEntity,
})
export class MallProductClothingController extends BaseController {
  @Inject()
  mallProductClothingService: MallProductClothingService;

  @Inject()
  mallProductService: MallProductService;

  @Post('/add')
  @Validate()
  async add(@Body(ALL) sku: NewSkuDTO) {
    const product = await this.mallProductService.info(sku.productId);
    if (!product) {
      return this.fail('请先添加商品再添加 SKU 信息', RESCODE.COMMFAIL);
    }

    try {
      const ret = await this.mallProductClothingService.add(sku);
      return this.ok(ret);
    } catch (e) {
      return this.fail(e.message, RESCODE.COMMFAIL);
    }
  }

  @Get('/list')
  async list(@Query(ALL) op: ListSkuDTO) {
    const skuList = await this.mallProductClothingService.list(op);
    return this.ok({
      productId: op.productId,
      skuList,
    });
  }
}
